package com.mediacloud.app.newsmodule.fragment


import android.annotation.SuppressLint
import android.text.TextUtils
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.RelativeLayout
import android.widget.TextView
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.BaseViewHolder
import com.eventTrack.CDPTrackReportManager
import com.eventTrack.TXReportManager
import com.facebook.drawee.view.SimpleDraweeView
import com.mediacloud.app.assembly.util.getArticleLogoUrl
import com.mediacloud.app.assembly.util.loadX
import com.mediacloud.app.fbnavsk.navPaddingTopMatch
import com.mediacloud.app.model.news.ArticleItem
import com.mediacloud.app.model.news.CatalogItem
import com.mediacloud.app.model.news.ShowSwitch
import com.mediacloud.app.nav2.fragment.HqyNavFragment
import com.mediacloud.app.newsmodule.R
import com.mediacloud.app.newsmodule.adaptor.cmsfieldstyle.NewsListUtil.setInfoView
import com.mediacloud.app.newsmodule.adaptor.cmsfieldstyle.NewsListUtil.setNewsItemTipV2
import com.mediacloud.app.newsmodule.adaptor.cmsfieldstyle.NewsListUtil.setNewsTitle
import com.mediacloud.app.newsmodule.utils.NewsItemClickUtils
import com.mediacloud.app.newsmodule.view.NewInfoView
import com.mediacloud.app.reslib.enums.AppFactoryGlobalConfig
import com.mediacloud.app.reslib.enums.ListStyle
import com.mediacloud.app.reslib.enums.ToolBarActionF5OrTop
import com.mediacloud.app.reslib.util.DataInvokeUtil
import com.mediacloud.app.user.model.UserInfo
import com.scwang.smartrefresh.layout.api.RefreshLayout
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener
import com.utils.ClickUtils
import com.utils.DisplayUtil
import com.utils.ExposurePoolService
import com.utils.read.ReadPlayView2
import io.reactivex.Observer
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.fragment_baserecyclerlistx.recyclerView
import kotlinx.android.synthetic.main.fragment_baserecyclerlistx.refreshLayout

/**
 * 安徽企点智能推荐导航
 */
class QDRecommendFragment : HqyNavFragment(), OnRefreshLoadMoreListener, ToolBarActionF5OrTop {
    var page = 1
    var dataList: MutableList<ArticleItem> = mutableListOf()
    val adapter by lazy {
        QDRecommenAdapter()
    }

    private var dataReady = false
    private val app_jhapp_video_impRunable: Runnable = Runnable {
        ExposurePoolService.getExecutorService().execute {
            try {
                TXReportManager.getExposureArticles(recyclerView, adapter.data)
                    ?.forEachIndexed { position,obj->
                        CDPTrackReportManager.getInstance()
                            .NewsRPExpose(position, obj)
                    }
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
    }
    private fun app_jhapp_video_imp() {
        if (!dataReady) return
        recyclerView?.apply {
            removeCallbacks(app_jhapp_video_impRunable)
            postDelayed(app_jhapp_video_impRunable, TXReportManager.EXPOSURE_DELAY)
        }
    }

    override fun choosed() {
        super.choosed()
        if (isAdded) {
            app_jhapp_video_imp()
        }
    }

    override fun getLayoutResID(): Int {
        return R.layout.fragment_baserecyclerlistx
    }

    override fun initView() {
        navPaddingTopMatch()
        loadingView = findViewById(R.id.mLoadingView)
        loadingView.setOnClickListener { v ->
            ClickUtils.delayClickable(v)
            if (currentState !== TYPE_LOADING) {
                showStateView(TYPE_LOADING, false)
                getData()
            }
        }
        initStateView()
        showStateView(TYPE_LOADING, false)
        val manager = LinearLayoutManager(requireContext())
        recyclerView.layoutManager = manager
        recyclerView.adapter = adapter
        refreshLayout.setOnRefreshLoadMoreListener(this)

        adapter.setOnItemClickListener { baseQuickAdapter, view, i ->
            val item = baseQuickAdapter.getItem(i) as ArticleItem
            CDPTrackReportManager.getInstance().NewsRPClick(i,item)
            NewsItemClickUtils.OpenItemNewsHandle(requireContext(), item.type, item, CatalogItem())
        }
        getData()
        recyclerView.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
                super.onScrollStateChanged(recyclerView, newState)
                if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                    app_jhapp_video_imp()
                }
            }
        })
    }

    private fun setData(data: MutableList<ArticleItem>) {
        refreshLayout.finishRefresh()
        refreshLayout.finishLoadMore()
        if (page == 2) {
            adapter.setNewData(dataList)
        } else {
            adapter.addData(data)
        }
        if (adapter.data.size == 0) {
            showStateView(TYPE_NO_CONTENT, false)
        } else {
            closeStateView()
        }
        dataReady = true
        if (hadChoosed) {
            app_jhapp_video_imp()
        }
    }

    @SuppressLint("CheckResult")
    fun getData() {
        var map = hashMapOf<String, Any>()
        val userInfo = UserInfo.getUserInfo(context)
        if (UserInfo.isLogin(context)) {
            map["mobile"] = userInfo.mobile
            map["user_id"] = userInfo.userid
        }
        map["page"] = page
        DataInvokeUtil.getZiMeiTiApi()
            .getQDRecommendList(map)
            .subscribeOn(Schedulers.io())
            .map {
                var articleItems = arrayListOf<ArticleItem>()
                if (it.optBoolean("state")) {
                    val data = it.optJSONObject("data")
                    data?.let {
                        val meta = data.optJSONArray("meta")
                        for (i in 0 until meta.length()) {
                            var item = ArticleItem.parse(meta.optJSONObject(i))
                            val showSwitch = ShowSwitch()
                            showSwitch.allowShowHitCount = true
                            showSwitch.allowShowInteractionCount = false
                            showSwitch.allowShowPublishDate = true
                            showSwitch.allowShowSource = true
                            showSwitch.allowShowComment = true
                            item.setmShowSwitch(showSwitch)
                            articleItems.add(item)
                        }
                    }
                }
                articleItems
            }
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(object : Observer<MutableList<ArticleItem>> {
                override fun onSubscribe(p0: Disposable) {

                }

                override fun onError(p0: Throwable) {
                    refreshLayout.finishRefresh()
                    if (adapter.data.size == 0) {
                        showStateView(TYPE_NO_CONTENT, false)
                    } else {
                        closeStateView()
                    }
                }

                override fun onComplete() {
                }

                override fun onNext(data: MutableList<ArticleItem>) {
                    if (page == 1) {
                        dataList.clear()
                        dataList.addAll(data)
                        page++
                        getData()
                    } else {
                        dataList.addAll(data)
                        setData(data)
                    }

                }

            })

    }


    class QDRecommenAdapter :
        BaseQuickAdapter<ArticleItem, BaseViewHolder>(R.layout.aappfactory_itemliststyle_basedefaultstyle_v2) {
        override fun convert(helper: BaseViewHolder, item: ArticleItem) {
            val newsTitle = helper.getView<TextView>(R.id.newsTitle)
            val stateLayout = helper.getView<ViewGroup>(R.id.stateLayout)
            val readPlayView = helper.getView<ReadPlayView2>(R.id.readPlayView)
            val stateText = helper.getView<TextView>(R.id.stateText)
            val infoView = helper.getView<NewInfoView>(R.id.infoView)
            val tvNewsTip = helper.getView<TextView>(R.id.tvNewsTip)
            val tvNewsTipV2 = helper.getView<TextView>(R.id.tvNewsTipV2)
            val txtLayout = helper.getView<View>(R.id.txtLayout)
            val iv_play_tag = helper.getView<ImageView>(R.id.iv_play_tag)
            val logoLayout = helper.getView<View>(R.id.imgLayout)
            val logoView = helper.getView<SimpleDraweeView>(R.id.guideImg)
            setNewsTitle(item, newsTitle, stateLayout, readPlayView, stateText)
            setNewsItemTipV2(
                item, tvNewsTip,
                null, iv_play_tag, tvNewsTipV2, null
            )
            setInfoView(helper.itemView, item, infoView, null)
            if (TextUtils.isEmpty(item.logo)) {
                logoLayout.setVisibility(View.INVISIBLE)
                logoLayout.getLayoutParams().width = 1
                logoLayout.getLayoutParams().height = DisplayUtil.dip2px(logoView.context, 50f)
                val layoutParams = RelativeLayout.LayoutParams(-1, -2)
                layoutParams.addRule(RelativeLayout.BELOW, R.id.txtLayout)
                layoutParams.addRule(RelativeLayout.ALIGN_START, R.id.txtLayout)
                layoutParams.addRule(RelativeLayout.ALIGN_END, R.id.txtLayout)
                layoutParams.topMargin = DisplayUtil.dip2px(logoView.context, 12f)
                infoView.layoutParams = layoutParams
            } else {
                logoLayout.setVisibility(View.VISIBLE)
                logoLayout.getLayoutParams().width = DisplayUtil.dip2px(logoView.context, 114f)
                logoLayout.getLayoutParams().height = DisplayUtil.dip2px(logoView.context, 84f)
                logoView.loadX(getArticleLogoUrl(4, 3, item), 1, 1, false, null)


                newsTitle.post {
                    val layoutParams =
                        infoView.layoutParams as RelativeLayout.LayoutParams
                    if (newsTitle.lineCount > 0) {
                        if (newsTitle.lineCount >= 3) {
                            if (newsTitle.lineCount >= 3) {
                                layoutParams.removeRule(RelativeLayout.ALIGN_BOTTOM)
                                layoutParams.addRule(RelativeLayout.BELOW, R.id.txtLayout)
                                layoutParams.topMargin = DisplayUtil.dip2px(logoView.context, 12f)
                            } else {
                                layoutParams.removeRule(RelativeLayout.BELOW)
                                layoutParams.addRule(RelativeLayout.ALIGN_BOTTOM, R.id.imgLayout)
                                layoutParams.topMargin = 0
                            }
                        } else {
                            layoutParams.removeRule(RelativeLayout.BELOW)
                            layoutParams.addRule(RelativeLayout.ALIGN_BOTTOM, R.id.imgLayout)
                            layoutParams.topMargin = 0
                        }
                    }
                    infoView.layoutParams = layoutParams
                }
            }
            val isLeftMode =
                ListStyle.TotoalStyle.LEFT_IMAGE == AppFactoryGlobalConfig.getAppServerConfigInfo(
                    mContext
                ).content_list
            logoView.loadX(getArticleLogoUrl(4, 3, item), 1, 1, false, null)
            val imgLayoutLayoutParams = logoLayout.layoutParams as RelativeLayout.LayoutParams
            val txtLayoutLayoutParams = txtLayout.layoutParams as RelativeLayout.LayoutParams
            val pd: Int = logoLayout.resources.getDimensionPixelSize(R.dimen.dimen16)
            if (isLeftMode) {
                imgLayoutLayoutParams.alignWithParent = true
                imgLayoutLayoutParams.addRule(RelativeLayout.ALIGN_PARENT_START)
                imgLayoutLayoutParams.removeRule(RelativeLayout.END_OF)
                imgLayoutLayoutParams.removeRule(RelativeLayout.ALIGN_PARENT_END)

                txtLayoutLayoutParams.removeRule(RelativeLayout.START_OF)
                if (txtLayoutLayoutParams.rules[RelativeLayout.END_OF] == 0) txtLayoutLayoutParams.addRule(
                    RelativeLayout.END_OF, R.id.imgLayout
                )
                txtLayoutLayoutParams.marginStart = pd


                imgLayoutLayoutParams.marginStart = 0
            } else {
                imgLayoutLayoutParams.alignWithParent = true
                imgLayoutLayoutParams.addRule(RelativeLayout.ALIGN_PARENT_END)
                imgLayoutLayoutParams.removeRule(RelativeLayout.END_OF)
                imgLayoutLayoutParams.removeRule(RelativeLayout.ALIGN_PARENT_START)

                txtLayoutLayoutParams.removeRule(RelativeLayout.END_OF)
                if (txtLayoutLayoutParams.rules[RelativeLayout.START_OF] == 0) txtLayoutLayoutParams.addRule(
                    RelativeLayout.START_OF, R.id.imgLayout
                )
                txtLayoutLayoutParams.marginStart = 0
                imgLayoutLayoutParams.marginStart = pd
            }
            txtLayout.setLayoutParams(txtLayoutLayoutParams)
            logoLayout.setLayoutParams(imgLayoutLayoutParams)
        }

    }

    override fun onRefresh(p0: RefreshLayout) {
        page = 1
        getData()
    }

    override fun onLoadMore(p0: RefreshLayout) {
        page++
        getData()
    }

    override fun f5() {
        recyclerView.scrollToPosition(0)
        refreshLayout.autoRefresh()
    }

    override fun gun() {
    }
}